[PowerShell] Sql Server SMO connection timeout not working

Posted by Uros Calakovic on Stack Overflow See other posts from Stack Overflow or by Uros Calakovic
Published on 2010-05-02T13:51:46Z Indexed on 2010/05/02 13:57 UTC
Read the original article Hit count: 638

I have the following PowerShell code:

function Get-SmoConnection
{
    param 
        ([string] $serverName = "", [int] $connectionTimeout = 0)

    if($serverName.Length -eq 0)
    {
        $serverConnection = New-Object `
            Microsoft.SqlServer.Management.Common.ServerConnection
    }
    else
    {
        $serverConnection = New-Object `
            Microsoft.SqlServer.Management.Common.ServerConnection($serverName)
    }

    if($connectionTimeout -ne 0)
    {
        $serverConnection.ConnectTimeout = $connectionTimeout
    }

    try
    {
        $serverConnection.Connect()
        $serverConnection
    }
    catch [system.Management.Automation.MethodInvocationException]
    {
        $null
    }


}

$connection = get-smoconnection "ServerName"  2

if($connection -ne $null)
{
    Write-Host $connection.ServerInstance
    Write-Host $connection.ConnectTimeout
}
else
{
    Write-Host "Connection could not be established"
}

It seems to work, except for the part that attempts to set the SMO connection timeout. If the connection is successful, I can verify that ServerConnection.ConnectTimeout is set to 2 (seconds), but when I supply a bogus name for the SQL Server instance, it still attempts to connect to it for ~ 15 seconds (which is I believe the default timeout value).

Does anyone have experience with setting SMO connection timeout? Thank you in advance.

© Stack Overflow or respective owner

Related posts about powershell

Related posts about smo